<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :lg="6" :xs="24">
        <div
          class="head-container"
          style="margin-bottom: 10px; padding-left: 60px"
        >
          <span
            style="
              font-family: 'Arial Normal', 'Arial', serif;
              font-weight: bold;
              font-size: 20px;
              letter-spacing: normal;
              line-height: normal;
              font-style: normal;
              color: #333333;
              text-align: center;
            "
            >组织结构</span
          >
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :default-expanded-keys="[100]"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            show-checkbox
            @check="handleCheckChange"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span v-if="data.label">
                <a class="treeTitle" :title="data.label">{{
                  data.label | ellipsis
                }}</a>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="18" :lg="18" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-if="showSearch"
          label-width="68px"
        >
          <el-form-item prop="examineCycle">
            <el-select
              v-model="queryParams.examineCycle"
              placeholder="请选择周期类型"
              @change="getCycleValue"
            >
              <el-option
                v-for="dict in dict.type.examine_cycle"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item prop="pickYear" v-if="showYearPicker">
            <el-date-picker
              v-model="queryParams.pickYear"
              type="year"
              placeholder="请选择年"
              @change="examineYearChange"
              :picker-options="examineYearOptions"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item
            prop="pickTemp"
            v-if="showCyclePicker"
            class="picker-cycle"
          >
            <el-select
              v-model="queryParams.pickTemp"
              multiple
              placeholder="请选择周期"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in dateOptions"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >统计</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          v-loading="loading"
          :data="statData"
          style="margin-bottom: 30px"
          v-if="showTable"
        >
          <el-table-column label="总人数" align="center" prop="allCount">
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="allcountHanlder"
                >{{ scope.row.allCount }}</el-link
              >
            </template>
          </el-table-column>
          <el-table-column
            label="优秀人数"
            align="center"
            prop="excellentCount"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="excellentHanlder"
                >{{ scope.row.excellentCount }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            label="优秀占比"
            align="center"
            prop="excellentScale"
          >
            <template slot-scope="scope">
              {{
                computeScale(scope.row.excellentCount, scope.row.allCount) + "%"
              }}
            </template>
          </el-table-column>
          <el-table-column label="良好人数" align="center" prop="goodCount">
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" @click="goodHanlder">{{
                scope.row.goodCount
              }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="良好占比" align="center" prop="goodScale">
            <template slot-scope="scope">
              {{ computeScale(scope.row.goodCount, scope.row.allCount) + "%" }}
            </template>
          </el-table-column>
          <el-table-column
            label="称职人数"
            align="center"
            prop="qualifiedCount"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="qualifiedHanlder"
                >{{ scope.row.qualifiedCount }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            label="称职占比"
            align="center"
            prop="qualifiedScale"
          >
            <template slot-scope="scope">
              {{
                computeScale(scope.row.qualifiedCount, scope.row.allCount) + "%"
              }}
            </template>
          </el-table-column>

          <el-table-column label="基本称职人数" align="center" prop="almostCount">
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" @click="almostHanlder">{{
                  scope.row.almostCount
                }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="基本称职占比" align="center" prop="almostScale">
            <template slot-scope="scope">
              {{ computeScale(scope.row.almostCount, scope.row.allCount) + "%" }}
            </template>
          </el-table-column>

          <el-table-column
            label="不称职人数"
            align="center"
            prop="unqualifiedCount"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="unqualifiedHanlder"
              >
                {{ scope.row.unqualifiedCount }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            label="不称职占比"
            align="center"
            prop="unqualifiedScale"
          >
            <template slot-scope="scope">
              {{
                computeScale(scope.row.unqualifiedCount, scope.row.allCount) +
                "%"
              }}
            </template>
          </el-table-column>
        </el-table>
        <div
          v-show="showPie"
          id="myChartsPie"
          style="width: 100%; height: 800px"
        ></div>
        <div
          v-show="showLine"
          id="myChartsLine"
          style="width: 1200%; height: 650px"
        ></div>
      </el-col>
    </el-row>
    <statistics-dialog
      ref="statisticsDialogRef"
      :export-method="handleExport"
    ></statistics-dialog>
  </div>
</template>

<script>
import { treeselect,treeselectAll } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  performanceStatistics,
  performanceStatisticsMore,
} from "@/api/examine/performance/api";
import echarts from "echarts";
import quarter from "@/views/tool/quarter";
import halfyear from "@/views/tool/halfyear";
import statisticsDialog from "@/views/examine/statisticsDialog";

export default {
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 10) {
        return value.slice(0, 10) + "...";
      }
      return value;
    },
  },
  name: "statistics",
  dicts: ["sys_normal_disable", "sys_user_sex", "examine_cycle"],
  components: {
    Treeselect,
    quarter,
    halfyear,
    statisticsDialog,
  },
  data() {
    return {
      echartsData: {},
      showYearPicker: false,
      showCyclePicker: false,
      dateOptions: [],
      chartDOMPie: null,
      chartDOMLine: null,
      cycleVal: "",
      showTable: true,
      showLine: false,
      showPie: true,
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 用户表格数据
      statData: [],
      // 部门树选项
      deptOptions: [],
      // 是否显示弹出层
      open: false,
      deptPickList: [],
      userTipOptions: [],
      // 部门名称
      deptName: undefined,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      examineYearOptions: {
        disabledDate: (time) => {
          const date = new Date();
          const year = date.getFullYear();
          const timeYear = time.getFullYear();
          return year > timeYear + 3;
        },
      },
      // 查询参数
      queryParams: {
        pickYear: undefined,
        examineYear: undefined,
        examineCycle: undefined,
        pickCycle: undefined,
        pickTemp: [],
        pickCycleText: undefined,
        deptSearchStr: "",
        examineResult: undefined,
        examineType: 0,
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    // this.getList();
    this.getTreeselect();
  },
  mounted() {},
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      performanceStatistics(this.queryParams)
        .then((response) => {
          this.echartsData = response.data;
          this.statData = [response.data];
          if (!this.showLine) {
            if (this.statData[0].allCount < 1) {
              this.statData = [];
              this.showTable = true;
              this.showPie = false;
            } else {
              this.initPieCharts(response.data);
              this.showTable = true;
              this.showPie = true;
            }
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    computeScale(item, all) {
      const number = ((item / all) * 100).toFixed(2);
      return (isFinite(number) && number) || 0;
    },
    initPieCharts(data) {
      var chartDOMPie = echarts.init(document.getElementById("myChartsPie"));
      chartDOMPie.setOption({
        legend: {
          orient: "horizontal",
          left: "right",
        },
        color: ["#3bb2fb", "#f2a694", "#f8ae30", "#c093de"],
        series: [
          {
            center: ["45%", "30%"],
            type: "pie",
            avoidLabelOverlap: true,
            radius: "50%",
            data: [
              { value: data.excellentCount, name: "优秀" },
              { value: data.goodCount, name: "良好" },
              { value: data.qualifiedCount, name: "称职" },
              { value: data.almostCount, name: "基本称职" },
              { value: data.unqualifiedCount, name: "不称职" },
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              normal: {
                formatter: "{c}人 ({d}%)",
                textStyle: { fontSize: "14", fontWeight: "bold" },
              },
            },
          },
        ],
      });
      chartDOMPie.on("click", (param) => {
        var index = param.dataIndex;
        if (index == 0) {
          this.excellentHanlder();
        } else if (index == 1) {
          this.goodHanlder();
        } else if (index == 2) {
          this.qualifiedHanlder();
        } else if (index == 3) {
          this.almostHanlder();
        } else if (index == 4) {
          this.unqualifiedHanlder();
        }
      });
    },
    initLineCharts(data) {
      var tempArr = [];
      var showDateArr = [];
      data.forEach((f) => {
        var obj = {};
        showDateArr.push(f.showDate);
        obj.name = f.showDate;
        obj.type = "line";
        // obj.stack = 'Total'
        obj.data = [
          f.excellentCount,
          f.goodCount,
          f.qualifiedCount,
          f.almostCount,
          f.unqualifiedCount,
        ];
        tempArr.push(obj);
      });
      var chartDOMLine = echarts.init(document.getElementById("myChartsLine"));
      chartDOMLine.setOption(
        {
          color: [
            "red",
            "blue",
            "black",
            "yellow",
            "#fac858",
            "#ee6666",
            "#8ede73",
            "rgba(8,234,106,0.49)",
            "#fc8452",
            "#9a60b4",
            "#ea7ccc",
            "#791515",
          ],
          title: {
            text: "单位：人",
            left: "90%",
            top: "30",
            textStyle: {
              fontSize: 12,
              color: "#797979",
            },
          },
          tooltip: {
            trigger: "axis",
          },
          legend: {
            orient: "horizontal",
            data: showDateArr,
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            boundaryGap: true,
            data: ["优秀", "良好", "称职", "基本称职", "不称职"],
          },
          yAxis: {
            type: "value",
            splitNumber: 5,
            minInterval: 5,
          },
          series: tempArr,
        },
        true
      );
    },
    // 全部跳转
    allcountHanlder() {
      this.queryParams.examineResult = null;
      this.queryParams.isSubmitted = null;
      this.routerJumper();
    },
    // 优秀跳转
    excellentHanlder() {
      this.queryParams.examineResult = 3;
      this.queryParams.isSubmitted = 1;
      this.routerJumper();
    },
    // 良好跳转
    goodHanlder() {
      this.queryParams.examineResult = 2;
      this.queryParams.isSubmitted = 1;
      this.routerJumper();
    },
    // 基本称职跳转
    almostHanlder() {
      this.queryParams.examineResult = 4;
      this.queryParams.isSubmitted = 1;
      this.routerJumper();
    },
    // 称职跳转
    qualifiedHanlder() {
      this.queryParams.examineResult = 1;
      this.queryParams.isSubmitted = 1;
      this.routerJumper();
    },
    // 不称职跳转
    unqualifiedHanlder() {
      this.queryParams.examineResult = 0;
      this.queryParams.isSubmitted = 1;
      this.routerJumper();
    },
    routerJumper() {
      this.$refs.statisticsDialogRef.dialogOpen(this.queryParams);
      // this.$router.push({path: "/performance/detail", query: {params: this.queryParams}});
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselectAll().then((response) => {
        this.deptOptions = response.data;
        this.$nextTick(() => {
          console.log(this.$refs.tree.getCheckedNodes().length);
          this.deptPickList = this.flatArr(response.data);
          // this.deptPickList = [{ id: 125 }];
          this.$refs.tree.setCheckedNodes(this.deptPickList);
          this.handleQuery();
        });

        // 全选 --> 并获得数据
        // this.$refs.tree.setCheckedNodes(this.deptOptions);
        // this.handleCheckChange();
      });
    },
    flatArr(arr) {
      // 数据扁平化
      return arr.flatMap((item) => {
        const { children = [], ...rest } = item;
        return [rest, ...this.flatArr(children)];
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleCheckChange() {
      //获取所有选中的节点id
      this.tenantIdMenus = this.$refs.tree.getCheckedNodes();
      this.deptPickList = this.tenantIdMenus;
      console.log(this.deptPickList);
    },
    getCycleValue(data) {
      this.dateOptions = [];
      this.queryParams.pickTemp = [];
      this.queryParams.pickCycleText = [];
      this.showYearPicker = true;
      if (data === "month") {
        this.dateOptions = [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ];
      } else if (data === "quarter") {
        this.dateOptions = ["第一季度", "第二季度", "第三季度", "第四季度"];
      } else if (data === "half_year") {
        this.dateOptions = ["上半年", "下半年"];
      } else if (data === "year") {
        this.showYearPicker = false;
        this.showCyclePicker = true;
        var currentYear = new Date().getFullYear();
        for (let i = 0; i <= 3; i++) {
          this.dateOptions.unshift(Number(currentYear) - i + "年");
        }
      }
      this.cycleVal = data;
    },
    // 表单重置
    reset() {
      this.form = {
        examineCycle: undefined,
        pickYear: undefined,
        pickTemp: undefined,
      };
      this.cycleVal = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pickCycleText = [];
      if (this.queryParams.examineYear) {
        this.queryParams.examineYear = this.queryParams.pickYear.getFullYear();
      }
      if (this.deptPickList) {
        this.queryParams.deptSearchStr = this.deptPickList
          .map((m) => m.id)
          .join(",");
      }
      if (this.queryParams.pickTemp.length > 0) {
        this.queryParams.pickCycleText = [...this.queryParams.pickTemp];
        if (this.queryParams.examineCycle !== "year") {
          for (let i = 0; i < this.queryParams.pickCycleText.length; i++) {
            if (
              (this.queryParams.pickCycleText &&
                this.queryParams.pickCycleText[i].indexOf("年") < 0) ||
              this.queryParams.examineCycle !== "quarter"
            ) {
              if (this.queryParams.examineCycle === "half_year") {
                if (this.queryParams.pickTemp[i].split("年").length - 1 < 2) {
                  // 防止重复点击拼接
                  this.queryParams.pickCycleText[i] =
                    this.queryParams.pickYear.getFullYear() +
                    "年 " +
                    this.queryParams.pickCycleText[i];
                }
              } else {
                if (
                  (this.queryParams.pickCycleText[i].match(/年/) || []).length <
                  1
                ) {
                  // 防止重复点击拼接
                  this.queryParams.pickCycleText[i] =
                    this.queryParams.pickYear.getFullYear() +
                    "年 " +
                    this.queryParams.pickCycleText[i];
                }
              }
            }
          }
        }
        this.queryParams.pickCycleText =
          this.queryParams.pickCycleText.join(",");
        if (this.queryParams.pickTemp.length > 1) {
          this.getStatisticsMore();
        } else {
          this.getList();
          this.showLine = false;
        }
      } else {
        this.getList();
        this.showLine = false;
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.showCyclePicker = false;
      this.showYearPicker = false;
      this.showLine = false;
      this.$refs.tree.setCheckedKeys([]);
      this.deptPickList = [];
      this.queryParams.pickCycleText = [];
      this.handleQuery();
    },
    // 多周期查询
    getStatisticsMore() {
      performanceStatisticsMore(this.queryParams).then((resp) => {
        this.showPie = false;
        this.showTable = false;
        this.showLine = true;
        this.initLineCharts(resp.rows);
      });
    },
    // 季度选择回调
    getQuarter(val) {
      this.queryParams.pickCycle = val;
    },
    // 半年度选择回调
    getHalfyear(val) {
      this.queryParams.pickCycle = val;
    },
    examineYearChange() {
      if (this.queryParams.examineCycle !== "year") {
        this.showCyclePicker = true;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      let examineResult = this.queryParams.examineResult;
      var text = "";
      if (examineResult == null) {
        text = "全部";
      } else if (examineResult == 3) {
        text = "优秀";
      } else if (examineResult == 2) {
        text = "良好";
      } else if (examineResult == 1) {
        text = "称职";
      } else {
        text = "不称职";
      }
      this.download(
        "examine/performance/detail/export",
        {
          ...this.queryParams,
        },
        "绩效考核" + text + "人员数据导出.xlsx"
      );
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .picker-cycle .el-input__inner {
  width: 355px;
}
</style>
